package com.example.zhinongbao.Fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridView;
import android.widget.SearchView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.zhinongbao.R;
import com.example.zhinongbao.activity.MyProductsActivity;
import com.example.zhinongbao.activity.NewsActivity;
import com.example.zhinongbao.activity.OrderManagementActivity;
import com.example.zhinongbao.activity.PublishProductActivity;
import com.example.zhinongbao.activity.SalesStatisticsActivity;
import com.example.zhinongbao.adapter.ProductAdapter;
import com.example.zhinongbao.adapter.SellerFunctionAdapter;
import com.example.zhinongbao.contract.HomeContract;
import com.example.zhinongbao.model.Product;
import com.example.zhinongbao.model.SellerFunction;
import com.example.zhinongbao.presenter.HomePresenter;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment implements HomeContract.View {
    private HomeContract.Presenter presenter;
    private ProductAdapter adapter;

    // 视图元素
    private View buyerView;
    private View sellerView;
    private boolean isSellerMode = false;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_home_container, container, false);

        // 初始化买家视图
        buyerView = inflater.inflate(R.layout.fragment_buyer_home, container, false);

        // 初始化卖家视图
        sellerView = inflater.inflate(R.layout.fragment_seller_home, container, false);

        // 将视图添加到容器
        ((ViewGroup) rootView).addView(buyerView);
        ((ViewGroup) rootView).addView(sellerView);

        // 初始化MVP
        presenter = new HomePresenter(this);

        // 初始化买家视图
        initBuyerView();

        // 初始化卖家视图
        initSellerView();

        // 设置默认视图
        toggleMode();

        // 加载商品数据
        presenter.loadProducts();
        return rootView;

    }
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 注册EventBus
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onProductAdded(PublishProductActivity.ProductAddedEvent event) {
        // 刷新商品列表
        presenter.loadProducts();
    }

    private void initBuyerView() {
        SearchView searchView = buyerView.findViewById(R.id.search_view);
        RecyclerView recyclerView = buyerView.findViewById(R.id.product_recycler_view);
        Button btnToSeller = buyerView.findViewById(R.id.btn_to_seller);

        // 设置去卖货按钮点击事件
        btnToSeller.setOnClickListener(v -> {
            isSellerMode = true;
            toggleMode();
        });

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                presenter.searchProducts(query);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                if (newText.isEmpty()) {
                    presenter.loadProducts();
                }
                return true;
            }
        });

        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new ProductAdapter(new ArrayList<>());
        recyclerView.setAdapter(adapter);
    }

    private void initSellerView() {
        // 初始化功能列表
        List<SellerFunction> functions = new ArrayList<>();
        functions.add(new SellerFunction("我的货品", R.drawable.ic_my_products, MyProductsActivity.class));
        functions.add(new SellerFunction("订单管理", R.drawable.ic_order_management, OrderManagementActivity.class));
        functions.add(new SellerFunction("新闻资讯", R.drawable.ic_news, NewsActivity.class));
        functions.add(new SellerFunction("销售统计", R.drawable.ic_sales_stats, SalesStatisticsActivity.class));

        // 设置适配器
        SellerFunctionAdapter adapter = new SellerFunctionAdapter(getContext(), functions);
        GridView sellerGrid = sellerView.findViewById(R.id.seller_grid);
        sellerGrid.setAdapter(adapter);

        // 设置点击事件 - 跳转到Activity
        sellerGrid.setOnItemClickListener((parent, view, position, id) -> {
            SellerFunction function = functions.get(position);
            Intent intent = new Intent(getActivity(), function.getTargetActivity());
            startActivity(intent);
        });

        // 设置去买货按钮点击事件
        Button btnToBuyer = sellerView.findViewById(R.id.btn_to_buyer);
        btnToBuyer.setOnClickListener(v -> {
            isSellerMode = false;
            toggleMode();
        });

    }

    private void toggleMode() {
        if (isSellerMode) {
            buyerView.setVisibility(View.GONE);
            sellerView.setVisibility(View.VISIBLE);
        } else {
            sellerView.setVisibility(View.GONE);
            buyerView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void showProducts(List<Product> products) {
        adapter.updateData(products);
    }

    @Override
    public void showSearchResults(List<Product> results) {
        adapter.updateData(results);
    }

    @Override
    public void showError(String message) {
        // 错误处理
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // 释放资源
        if (buyerView != null) {
            ((ViewGroup) buyerView.getParent()).removeView(buyerView);
        }
        if (sellerView != null) {
            ((ViewGroup) sellerView.getParent()).removeView(sellerView);
        }
        super.onDestroyView();
        // 注销EventBus
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}